import React, { memo, useEffect, useState } from "react";
import type { FC, ReactNode } from "react";
import { PlayListWrapper } from "./style";
import { useParams } from "react-router-dom";
import { useAppDispatch, useAppSelector } from "@/store";
import { feachMenuDetailAction } from "./store";
import AreaHeaderv2 from "@/components/area-headerv2";
import AreaModalv1 from "@/components/area-modalv1";
import { shallowEqual } from "react-redux";
import AreaItemv3 from "@/components/area-itemv3";

interface IProps {
  children?: ReactNode;
}

const PlayList: FC<IProps> = () => {
  const params = useParams()
  const { menuId } = params

  // 控制modal显示隐藏
  const [isDesModal, setIsModal] = useState(0)
  // 控制当前的页码
  const [currPage, setCurrPage] = useState(1)
  // 控制偏移量
  const dispatch = useAppDispatch()
  useEffect(() => {
    dispatch(feachMenuDetailAction({ id: Number(menuId), offset: (currPage - 1) * 50 }))
  }, [dispatch, menuId, currPage])

  const { menuDetail, menuTranks } = useAppSelector((state) => ({
    menuDetail: state.playlist.menuDetail,
    menuTranks: state.playlist.menuTranks
  }), shallowEqual)

  // 弹窗的显示隐藏方法
  const handleCancel = (isDes: number) => {
    setIsModal(isDes)
  }

  // 加载更多方法
  const handleUpload = () => {
    setCurrPage(currPage + 1)
  }

  // 歌单路由组件
  return <PlayListWrapper>
    {Object.keys(menuDetail).length > 0 && menuTranks.length > 0 &&
      <AreaHeaderv2 itemData={menuDetail} playList={menuTranks} onShowDesFn={handleCancel} isHeaderType="playlist" />
    }
    {menuTranks.length > 0 &&
      <div className="playlist-container">
        {
          menuTranks.map(item => (
            <AreaItemv3 key={item.id} itemData={item} />
          ))
        }
      </div>
    }
    {
      menuTranks.length > 0 &&
      <div className="uploads" onClick={handleUpload} style={{ opacity: menuTranks.length === menuDetail.trankIds ? 0 : 1 }}>加载更多</div>
    }
    {Object.keys(menuDetail).length > 0 &&
      <AreaModalv1 modalText="歌曲" onCancel={handleCancel} modelDes={menuDetail.description} isDesModal={isDesModal} />
    }
  </PlayListWrapper>;
};

export default memo(PlayList);